// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.DataIndex;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearchFilter;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.Platformshipping;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryExchangeVo;
import com.fowo.api.inventory.model.InventoryOutboundVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.model.form.InventoryOutboundFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.LogisticsChannelMapper;
import com.fowo.api.mapper.LogisticsProviderMapper;
import com.fowo.api.mapper.PlatformshippingItemMapper;
import com.fowo.api.mapper.PlatformshippingMapper;
import com.fowo.api.mapper.PlatformshippinglogisticsMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.logistics.channel.LogisticsChannelItemVo;
import com.fowo.api.model.logistics.channel.LogisticsChannelSearchParamPo;
import com.fowo.api.model.logistics.provider.LogisticsProviderItemVo;
import com.fowo.api.model.logistics.provider.LogisticsProviderSearchParamPo;
import com.fowo.api.model.platformshipping.PlatformshippingAllocateInventoryAction;
import com.fowo.api.model.platformshipping.PlatformshippingBatchcompletionpickingAction;
import com.fowo.api.model.platformshipping.PlatformshippingCancelOrderAction;
import com.fowo.api.model.platformshipping.PlatformshippingExcelPo;
import com.fowo.api.model.platformshipping.PlatformshippingImportPo;
import com.fowo.api.model.platformshipping.PlatformshippingItemVo;
import com.fowo.api.model.platformshipping.PlatformshippingReleaseInventoryAction;
import com.fowo.api.model.platformshipping.PlatformshippingSearchParamPo;
import com.fowo.api.model.platformshipping.PlatformshippingSendoutgoodsAction;
import com.fowo.api.model.platformshipping.PlatformshippingVo;
import com.fowo.api.model.platformshipping.constant.PlatformshippingHeadfeetypeEnums;
import com.fowo.api.model.platformshipping.constant.PlatformshippingIsinventorylockedEnums;
import com.fowo.api.model.platformshipping.constant.PlatformshippingOrderlogisticsstatusEnums;
import com.fowo.api.model.platformshipping.constant.PlatformshippingPickingnotEnums;
import com.fowo.api.model.platformshipping.constant.PlatformshippingShippingstatusEnums;
import com.fowo.api.model.platformshipping.item.PlatformshippingItemItemVo;
import com.fowo.api.model.platformshipping.item.PlatformshippingItemItemVoPages;
import com.fowo.api.model.platformshipping.item.PlatformshippingItemSearchParamPo;
import com.fowo.api.model.platformshippinglogistics.PlatformshippinglogisticsSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.PlatformshippingItemService;
import com.fowo.api.service.PlatformshippingService;
import com.fowo.api.service.PlatformshippinglogisticsService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 平台仓发货单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：王阳阳，沈友谅
 */
@Slf4j
@DataObjectType(Platformshipping.class)
@DS("ds24")
public class PlatformshippingBaseServiceImpl
  extends ServiceImpl<PlatformshippingMapper, Platformshipping>
  implements PlatformshippingService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("deliverywarehouseName", "w.`name`");
      put("logisticsproviderName", "lp.`name`");
      put("logisticsproviderIdName", "lc.`name`");
      put("sendgoodspeopleName", "su.`name`");
      put("principalusernameName", "su2.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected PlatformshippingService self;

  @Resource
  protected PlatformshippingItemService platformshippingItemService;

  @Resource
  protected PlatformshippinglogisticsService platformshippinglogisticsService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected LogisticsProviderMapper logisticsProviderMapper;

  @Resource
  protected LogisticsChannelMapper logisticsChannelMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected PlatformshippingCancelOrderAction platformshippingCancelOrderAction;

  @Autowired(required = false)
  protected PlatformshippingReleaseInventoryAction platformshippingReleaseInventoryAction;

  @Autowired(required = false)
  protected PlatformshippingSendoutgoodsAction platformshippingSendoutgoodsAction;

  @Autowired(required = false)
  protected PlatformshippingAllocateInventoryAction platformshippingAllocateInventoryAction;

  @Autowired(required = false)
  protected PlatformshippingBatchcompletionpickingAction platformshippingBatchcompletionpickingAction;

  @Resource
  protected Validator validator;

  /**
   * 创建平台仓发货单
   * @param model 平台仓发货单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(PlatformshippingVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Platformshipping entity = new Platformshipping();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getShippingstatus() == null) {
      entity.setShippingstatus("0");
    }

    if (model.getHeadfeetype() == null) {
      entity.setHeadfeetype("0");
    }

    if (model.getIsinventorylocked() == null) {
      entity.setIsinventorylocked("1");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getShipmentCode())) {
      entity.setShipmentCode(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "Platformshipping.shipmentCode")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("平台仓发货单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 平台仓发货单
   */
  protected void updateAllChilds(PlatformshippingVo model) throws Exception {
    if (model.getItems() != null) {
      platformshippingItemService.saveAllByParentPlatformshipping(
        model.getId(),
        model.getItems()
      );
    }

    if (model.getLogisticsItems() != null) {
      platformshippinglogisticsService.saveAllByParentPlatformshipping(
        model.getId(),
        model.getLogisticsItems()
      );
    }
  }

  /**
   * 更新平台仓发货单
   * @param model 平台仓发货单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(PlatformshippingVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Platformshipping entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("平台仓发货单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "deliverywarehouse",
      "createUser",
      "createTime",
      "lastUpdateTime",
      "logisticscode",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新平台仓发货单（带空值）
   * @param model 平台仓发货单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(PlatformshippingVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Platformshipping entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("平台仓发货单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(Platformshipping::getLastUpdateTime, model.getLastUpdateTime())
      .set(Platformshipping::getArrivaltime, model.getArrivaltime())
      .set(Platformshipping::getSailtime, model.getSailtime())
      .set(
        Platformshipping::getExpectedarrivaltime,
        model.getExpectedarrivaltime()
      )
      .set(Platformshipping::getActualdueime, model.getActualdueime())
      .set(
        Platformshipping::getActualdeliverytime,
        model.getActualdeliverytime()
      )
      .set(Platformshipping::getRemarks, model.getRemarks())
      .set(Platformshipping::getLastUpdateUser, model.getLastUpdateUser())
      .set(Platformshipping::getLogisticsprovider, model.getLogisticsprovider())
      .set(
        Platformshipping::getLogisticsproviderId,
        model.getLogisticsproviderId()
      )
      .set(
        Platformshipping::getOrderlogisticsstatus,
        model.getOrderlogisticsstatus()
      )
      .set(
        model.getFj() != null,
        Platformshipping::getFj,
        JSON.toJSONString(model.getFj())
      )
      .setSql(model.getFj() == null, "fj = null")
      .eq(Platformshipping::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(PlatformshippingSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 发货商品(items) 对应的对象
    PlatformshippingItemSearchParamPo itemsSearchParam =
      new PlatformshippingItemSearchParamPo();
    itemsSearchParam.setDisableDataPremissions(true);
    itemsSearchParam.setParentPlatformshippingInList(ids);
    PlatformshippingItemMapper localPlatformshippingItemMapper = ContextHolder
      .getApplicationContext()
      .getBean(PlatformshippingItemMapper.class);
    itemsSearchParam.applySqlSegments();
    List<Long> itemsIdList = localPlatformshippingItemMapper.searchIds(
      itemsSearchParam
    );
    if (!itemsIdList.isEmpty()) {
      PlatformshippingItemService localPlatformshippingItemService =
        ContextHolder
          .getApplicationContext()
          .getBean(PlatformshippingItemService.class);
      localPlatformshippingItemService.batchDelete(itemsIdList);
    }

    // 处理子表字段 物流信息(logisticsItems) 对应的对象
    PlatformshippinglogisticsSearchParamPo logisticsItemsSearchParam =
      new PlatformshippinglogisticsSearchParamPo();
    logisticsItemsSearchParam.setDisableDataPremissions(true);
    logisticsItemsSearchParam.setParentPlatformshippingInList(ids);
    PlatformshippinglogisticsMapper localPlatformshippinglogisticsMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(PlatformshippinglogisticsMapper.class);
    logisticsItemsSearchParam.applySqlSegments();
    List<Long> logisticsItemsIdList =
      localPlatformshippinglogisticsMapper.searchIds(logisticsItemsSearchParam);
    if (!logisticsItemsIdList.isEmpty()) {
      PlatformshippinglogisticsService localPlatformshippinglogisticsService =
        ContextHolder
          .getApplicationContext()
          .getBean(PlatformshippinglogisticsService.class);
      localPlatformshippinglogisticsService.batchDelete(logisticsItemsIdList);
    }
  }

  /**
   * 删除平台仓发货单
   * @param id 平台仓发货单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除平台仓发货单
   * @param ids 平台仓发货单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<PlatformshippingImportPo> excelToImportRow(
    PlatformshippingImportPo row,
    Integer rowNumber,
    PlatformshippingVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<PlatformshippingImportPo> ir =
      new ImportRow<PlatformshippingImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<PlatformshippingImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new PlatformshippingVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, PlatformshippingImportPo.class);

    // 一般数据处理
    vo.setDeliveryTime(SheetUtils.tryToDate(row.getDeliveryTime()));
    SheetUtils.datePreviewFormat(row.getDeliveryTime(), row::setDeliveryTime);
    if (StringUtils.hasText(row.getShippingstatus())) {
      vo.setShippingstatus(
        PlatformshippingShippingstatusEnums.toValue(row.getShippingstatus())
      );
      if (vo.getShippingstatus() == null) {
        ir.addError(
          "shippingstatus",
          "发货状态只能是：“待配货”, “待发货”, “已发货”, “已作废”"
        );
      }
    }
    vo.setArrivaltime(SheetUtils.tryToDate(row.getArrivaltime()));
    SheetUtils.datePreviewFormat(row.getArrivaltime(), row::setArrivaltime);
    vo.setSailtime(SheetUtils.tryToDate(row.getSailtime()));
    SheetUtils.datePreviewFormat(row.getSailtime(), row::setSailtime);
    vo.setExpectedarrivaltime(
      SheetUtils.tryToDate(row.getExpectedarrivaltime())
    );
    SheetUtils.datePreviewFormat(
      row.getExpectedarrivaltime(),
      row::setExpectedarrivaltime
    );
    vo.setActualdueime(SheetUtils.tryToDate(row.getActualdueime()));
    SheetUtils.datePreviewFormat(row.getActualdueime(), row::setActualdueime);
    vo.setActualdeliverytime(SheetUtils.tryToDate(row.getActualdeliverytime()));
    SheetUtils.datePreviewFormat(
      row.getActualdeliverytime(),
      row::setActualdeliverytime
    );
    if (StringUtils.hasText(row.getHeadfeetype())) {
      vo.setHeadfeetype(
        PlatformshippingHeadfeetypeEnums.toValue(row.getHeadfeetype())
      );
      if (vo.getHeadfeetype() == null) {
        ir.addError(
          "headfeetype",
          "分摊方式只能是：“按计费重”, “按实重”, “按体积重”, “按SKU”, “按箱子体积”, “自定义”"
        );
      }
    }
    if (StringUtils.hasText(row.getOrderlogisticsstatus())) {
      vo.setOrderlogisticsstatus(
        PlatformshippingOrderlogisticsstatusEnums.toValue(
          row.getOrderlogisticsstatus()
        )
      );
      if (vo.getOrderlogisticsstatus() == null) {
        ir.addError(
          "orderlogisticsstatus",
          "订单物流状态只能是：“状态1”, “状态2”"
        );
      }
    }
    if (StringUtils.hasText(row.getIsinventorylocked())) {
      vo.setIsinventorylocked(
        PlatformshippingIsinventorylockedEnums.toValue(
          row.getIsinventorylocked()
        )
      );
      if (vo.getIsinventorylocked() == null) {
        ir.addError("isinventorylocked", "是否锁库存只能是：“是”, “否”");
      }
    }
    if (StringUtils.hasText(row.getPickingnot())) {
      vo.setPickingnot(
        PlatformshippingPickingnotEnums.toValue(row.getPickingnot())
      );
      if (vo.getPickingnot() == null) {
        ir.addError("pickingnot", "拣货状态只能是：“是”, “否”");
      }
    }
    // 处理关联字段“发货仓库”
    if (
      !SheetUtils.isBlank(row.getDeliverywarehouseName()) &&
      SheetUtils.isBlank(row.getDeliverywarehouse())
    ) {
      WarehouseSearchParamPo deliverywarehouseSearchParam =
        new WarehouseSearchParamPo();
      deliverywarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      deliverywarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getDeliverywarehouseName())
      );
      deliverywarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> deliverywarehouseMatches = warehouseMapper.search(
        deliverywarehouseSearchParam
      );
      if (deliverywarehouseMatches.size() == 0) {
        ir.addError(
          "deliverywarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (deliverywarehouseMatches.size() > 1) {
        ir.addError(
          "deliverywarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setDeliverywarehouse(deliverywarehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流商”
    if (
      !SheetUtils.isBlank(row.getLogisticsproviderName()) &&
      SheetUtils.isBlank(row.getLogisticsprovider())
    ) {
      LogisticsProviderSearchParamPo logisticsproviderSearchParam =
        new LogisticsProviderSearchParamPo();
      logisticsproviderSearchParam.setLimit(2); // 最大只返回二行记录
      logisticsproviderSearchParam.setNameEq(
        SheetUtils.trim(row.getLogisticsproviderName())
      );
      logisticsproviderSearchParam.applySqlSegments();
      List<LogisticsProviderItemVo> logisticsproviderMatches =
        logisticsProviderMapper.search(logisticsproviderSearchParam);
      if (logisticsproviderMatches.size() == 0) {
        ir.addError("logisticsproviderName", "未能在物流商中找到匹配的数据");
      } else if (logisticsproviderMatches.size() > 1) {
        ir.addError(
          "logisticsproviderName",
          "关联不唯一，在物流商中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsprovider(logisticsproviderMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流方式”
    if (
      !SheetUtils.isBlank(row.getLogisticsproviderIdName()) &&
      SheetUtils.isBlank(row.getLogisticsproviderId())
    ) {
      LogisticsChannelSearchParamPo logisticsproviderIdSearchParam =
        new LogisticsChannelSearchParamPo();
      logisticsproviderIdSearchParam.setLimit(2); // 最大只返回二行记录
      logisticsproviderIdSearchParam.setNameEq(
        SheetUtils.trim(row.getLogisticsproviderIdName())
      );
      logisticsproviderIdSearchParam.setFinalFilters(new ArrayList<>());
      logisticsproviderIdSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("channelName"))
            .setOp("eq")
            .setValue(SheetUtils.toString(vo.getLogisticsprovider()))
        );
      logisticsproviderIdSearchParam.applySqlSegments();
      List<LogisticsChannelItemVo> logisticsproviderIdMatches =
        logisticsChannelMapper.search(logisticsproviderIdSearchParam);
      if (logisticsproviderIdMatches.size() == 0) {
        ir.addError(
          "logisticsproviderIdName",
          "未能在物流渠道中找到匹配的数据"
        );
      } else if (logisticsproviderIdMatches.size() > 1) {
        ir.addError(
          "logisticsproviderIdName",
          "关联不唯一，在物流渠道中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsproviderId(logisticsproviderIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“发货人”
    if (
      !SheetUtils.isBlank(row.getSendgoodspeopleName()) &&
      SheetUtils.isBlank(row.getSendgoodspeople())
    ) {
      SysUserSearch sendgoodspeopleSearchParam = new SysUserSearch();
      sendgoodspeopleSearchParam.setLimit(2); // 最大只返回二行记录
      sendgoodspeopleSearchParam.setNameEq(
        SheetUtils.trim(row.getSendgoodspeopleName())
      );
      sendgoodspeopleSearchParam.applySqlSegments();
      List<SysUserItemVo> sendgoodspeopleMatches = sysUserMapper.search(
        sendgoodspeopleSearchParam
      );
      if (sendgoodspeopleMatches.size() == 0) {
        ir.addError("sendgoodspeopleName", "未能在用户中找到匹配的数据");
      } else if (sendgoodspeopleMatches.size() > 1) {
        ir.addError(
          "sendgoodspeopleName",
          "关联不唯一，在用户中找到多个匹配的数据"
        );
      } else {
        vo.setSendgoodspeople(sendgoodspeopleMatches.get(0).getId());
      }
    }
    // 处理关联字段“负责人”
    if (
      !SheetUtils.isBlank(row.getPrincipalusernameName()) &&
      SheetUtils.isBlank(row.getPrincipalusername())
    ) {
      SysUserSearch principalusernameSearchParam = new SysUserSearch();
      principalusernameSearchParam.setLimit(2); // 最大只返回二行记录
      principalusernameSearchParam.setNameEq(
        SheetUtils.trim(row.getPrincipalusernameName())
      );
      principalusernameSearchParam.applySqlSegments();
      List<SysUserItemVo> principalusernameMatches = sysUserMapper.search(
        principalusernameSearchParam
      );
      if (principalusernameMatches.size() == 0) {
        ir.addError("principalusernameName", "未能在用户中找到匹配的数据");
      } else if (principalusernameMatches.size() > 1) {
        ir.addError(
          "principalusernameName",
          "关联不唯一，在用户中找到多个匹配的数据"
        );
      } else {
        vo.setPrincipalusername(principalusernameMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<PlatformshippingImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<PlatformshippingImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            PlatformshippingImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              PlatformshippingImportPo row,
              AnalysisContext cxt
            ) {
              PlatformshippingVo vo = new PlatformshippingVo();
              ImportRow<PlatformshippingImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<PlatformshippingImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<PlatformshippingImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      PlatformshippingVo vo = new PlatformshippingVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"发货单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "shipmentCode".equals(m.getField())
          )
      ) {
        vo.setShipmentCode(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "Platformshipping.shipmentCode")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    PlatformshippingSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "deliverywarehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((PlatformshippingItemVo) r).getDeliverywarehouseName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryTime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "shippingstatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PlatformshippingShippingstatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "arrivaltime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "sailtime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "expectedarrivaltime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "actualdueime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "actualdeliverytime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "logisticsprovider",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((PlatformshippingItemVo) r).getLogisticsproviderName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "logisticsproviderId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((PlatformshippingItemVo) r).getLogisticsproviderIdName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "headfeetype",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PlatformshippingHeadfeetypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "sendgoodspeople",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((PlatformshippingItemVo) r).getSendgoodspeopleName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "orderlogisticsstatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PlatformshippingOrderlogisticsstatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "principalusername",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((PlatformshippingItemVo) r).getPrincipalusernameName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "pickingnot",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PlatformshippingPickingnotEnums.toLabel((String) o)
          )
      );
      exportOptions.addStringFields(
        "shipmentCode",
        "deliverywarehouseName",
        "shippingstatus",
        "logisticscode",
        "logisticsInfo",
        "remarks",
        "logisticsproviderName",
        "logisticsproviderIdName",
        "headfeetype",
        "sendgoodspeopleName",
        "orderlogisticsstatus",
        "principalusernameName",
        "pickingnot"
      );

      String fileName = String.format(
        "平台仓发货单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<PlatformshippingExcelPo> items =
      new ArrayList<PlatformshippingExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<PlatformshippingItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<PlatformshippingItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (PlatformshippingItemVo item : list) {
        PlatformshippingExcelPo excel = new PlatformshippingExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setShippingstatus(
          PlatformshippingShippingstatusEnums.toLabel(item.getShippingstatus())
        );
        excel.setHeadfeetype(
          PlatformshippingHeadfeetypeEnums.toLabel(item.getHeadfeetype())
        );
        excel.setOrderlogisticsstatus(
          PlatformshippingOrderlogisticsstatusEnums.toLabel(
            item.getOrderlogisticsstatus()
          )
        );
        excel.setPickingnot(
          PlatformshippingPickingnotEnums.toLabel(item.getPickingnot())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "平台仓发货单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(PlatformshippingExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过发货单号查询平台仓发货单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByShipmentCode(String shipmentCode) {
    return this.baseMapper.getIdByShipmentCode(shipmentCode);
  }

  /**
   * 通过发货单号查询平台仓发货单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByShipmentCode(List<String> list) {
    return this.baseMapper.getIdsByShipmentCode(list);
  }

  /**
   * 通过平台仓发货单主键查询发货单号
   */
  @Override
  public String getShipmentCodeById(Long id) {
    return this.baseMapper.getShipmentCodeById(id);
  }

  /**
   * 通过平台仓发货单主键查询发货单号列表
   */
  @Override
  public List<String> getShipmentCodeByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getShipmentCodeByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("shipmentCode"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 平台仓发货单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public PlatformshippingVo getVoById(Long id) throws Exception {
    PlatformshippingVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    PlatformshippingItemSearchParamPo itemsSearchParamPo =
      new PlatformshippingItemSearchParamPo();
    itemsSearchParamPo.setParentPlatformshipping(id);
    itemsSearchParamPo.getExtendData().put("queryMode", "sub");
    itemsSearchParamPo.getExtendData().put("queryParent", "Platformshipping");
    itemsSearchParamPo.applySqlSegments();
    vo.setItems(platformshippingItemService.search(itemsSearchParamPo));

    PlatformshippinglogisticsSearchParamPo logisticsItemsSearchParamPo =
      new PlatformshippinglogisticsSearchParamPo();
    logisticsItemsSearchParamPo.setParentPlatformshipping(id);
    logisticsItemsSearchParamPo.getExtendData().put("queryMode", "sub");
    logisticsItemsSearchParamPo
      .getExtendData()
      .put("queryParent", "Platformshipping");
    logisticsItemsSearchParamPo.applySqlSegments();
    vo.setLogisticsItems(
      platformshippinglogisticsService.search(logisticsItemsSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询平台仓发货单
   * @param search 查询条件
   * @return 平台仓发货单分页查询结果
   */
  @Override
  public Page<PlatformshippingItemVo> pageSearch(
    PlatformshippingSearchParamPo search
  ) {
    Page<PlatformshippingItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(PlatformshippingItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<PlatformshippingItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<PlatformshippingItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    PlatformshippingItemSearchParamPo itemsSearchParamPo =
      new PlatformshippingItemSearchParamPo();
    itemsSearchParamPo.setSort(sort);
    itemsSearchParamPo.setPageSize(5);
    itemsSearchParamPo.setParentPlatformshippingInList(
      pageResult
        .getRecords()
        .stream()
        .map(PlatformshippingItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<PlatformshippingItemItemVoPages>> itemsMaps =
      platformshippingItemService.pagesByParentPlatformshipping(
        itemsSearchParamPo
      );

    for (PlatformshippingItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put("items", itemsMaps.get(itemVo.getId().toString()));
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 平台仓发货单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(PlatformshippingSearchParamPo search) {
    return appendWithChild(pageSearch(search), search.toChildSort("items"));
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    PlatformshippingSearchParamPo search
  ) {
    PlatformshippingSearchParamPo parentSearchParam =
      new PlatformshippingSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<PlatformshippingItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      PlatformshippingItemVo itemVo = parentList.get(0);

      PlatformshippingItemSearchParamPo itemsSearchParamPo =
        new PlatformshippingItemSearchParamPo();
      itemsSearchParamPo.setPageSize(search.getPageSize());
      itemsSearchParamPo.setCurrent(search.getCurrent());
      itemsSearchParamPo.setParentPlatformshipping(itemVo.getId());
      return platformshippingItemService.pageSearch(itemsSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 平台仓发货单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'PlatformshippingOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<PlatformshippingItemVo>> searchOptions(
    PlatformshippingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询平台仓发货单
   * @param search 查询条件
   * @return 平台仓发货单列表查询结果
   */
  @Override
  public List<PlatformshippingItemVo> search(
    PlatformshippingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询平台仓发货单最后更新时间
   * @param search 查询条件
   * @return 平台仓发货单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(PlatformshippingSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 取消锁库存_仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消锁库存_仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelLockpInventory(Long id) throws Exception {
    PlatformshippingVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareCancelLockpInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Platformshipping updateStatusEntity = new Platformshipping();
    updateStatusEntity.setId(id);
    updateStatusEntity.setShippingstatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消锁库存_仓位 的参数
   */
  protected InventoryExchangeFormVo prepareCancelLockpInventory(
    PlatformshippingVo vo
  ) throws Exception {
    if (!"0".equals(vo.getShippingstatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(PlatformshippingVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getShipmentCode());
    formVo.setDocumentType("取消平台发货锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliverywarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliverywarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (PlatformshippingItemItemVo platformshippingItem : vo.getItems()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(platformshippingItem.getProductName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(platformshippingItem.getShipmentsnum())
      );
      exchangeItem.setShopId(
        String
            .valueOf(platformshippingItem.getShippingwarehousestore())
            .equals("null")
          ? null
          : String.valueOf(platformshippingItem.getShippingwarehousestore())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            platformshippingItem.getFnsku() == null
              ? null
              : platformshippingItem.getFnsku().trim()
          )
          ? null
          : String.valueOf(platformshippingItem.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        platformshippingItem.getBinid(),
        Integer.parseInt(
          String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
            ? "0"
            : String.valueOf(platformshippingItem.getShipmentsnum())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        platformshippingItem.getBinid(),
        Integer.parseInt(
          String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
            ? "0"
            : String.valueOf(platformshippingItem.getShipmentsnum())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(platformshippingItem.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 取消锁库存_即时
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消锁库存_即时操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelLocksInventory(Long id) throws Exception {
    PlatformshippingVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareCancelLocksInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Platformshipping updateStatusEntity = new Platformshipping();
    updateStatusEntity.setId(id);
    updateStatusEntity.setShippingstatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消锁库存_即时 的参数
   */
  protected InventoryExchangeFormVo prepareCancelLocksInventory(
    PlatformshippingVo vo
  ) throws Exception {
    if (!"0".equals(vo.getShippingstatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(PlatformshippingVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getShipmentCode());
    formVo.setDocumentType("取消平台仓锁库存");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliverywarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliverywarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (PlatformshippingItemItemVo platformshippingItem : vo.getItems()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(platformshippingItem.getProductName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(platformshippingItem.getShipmentsnum())
      );
      exchangeItem.setShopId(
        String
            .valueOf(platformshippingItem.getShippingwarehousestore())
            .equals("null")
          ? null
          : String.valueOf(platformshippingItem.getShippingwarehousestore())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            platformshippingItem.getFnsku() == null
              ? null
              : platformshippingItem.getFnsku().trim()
          )
          ? null
          : String.valueOf(platformshippingItem.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(platformshippingItem.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 出库锁定
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库锁定操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockStockOut(Long id) throws Exception {
    PlatformshippingVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareLockStockOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    Platformshipping updateStatusEntity = new Platformshipping();
    updateStatusEntity.setId(id);
    updateStatusEntity.setShippingstatus("2");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 出库锁定 的参数
   */
  protected InventoryOutboundFormVo prepareLockStockOut(PlatformshippingVo vo)
    throws Exception {
    if (!"1".equals(vo.getShippingstatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(PlatformshippingVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getShipmentCode());
    formVo.setDocumentType("平台发货单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getDeliverywarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (PlatformshippingItemItemVo platformshippingItem : vo.getItems()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(platformshippingItem.getProductName());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(platformshippingItem.getShipmentsnum())
      );
      outboundItem.setShopId(
        String
            .valueOf(platformshippingItem.getShippingwarehousestore())
            .equals("null")
          ? null
          : String.valueOf(platformshippingItem.getShippingwarehousestore())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            platformshippingItem.getFnsku() == null
              ? null
              : platformshippingItem.getFnsku().trim()
          )
          ? null
          : String.valueOf(platformshippingItem.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        platformshippingItem.getBinid(),
        Integer.parseInt(
          String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
            ? "0"
            : String.valueOf(platformshippingItem.getShipmentsnum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Lock);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(platformshippingItem.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 锁库存_仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存_仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockpInventory(Long id) throws Exception {
    PlatformshippingVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockpInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Platformshipping updateStatusEntity = new Platformshipping();
    updateStatusEntity.setId(id);
    updateStatusEntity.setShippingstatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存_仓位 的参数
   */
  protected InventoryExchangeFormVo prepareLockpInventory(
    PlatformshippingVo vo
  ) throws Exception {
    if (!"0".equals(vo.getShippingstatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(PlatformshippingVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getShipmentCode());
    formVo.setDocumentType("平台发货单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliverywarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliverywarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (PlatformshippingItemItemVo platformshippingItem : vo.getItems()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(platformshippingItem.getProductName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(platformshippingItem.getShipmentsnum())
      );
      exchangeItem.setShopId(
        String
            .valueOf(platformshippingItem.getShippingwarehousestore())
            .equals("null")
          ? null
          : String.valueOf(platformshippingItem.getShippingwarehousestore())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            platformshippingItem.getFnsku() == null
              ? null
              : platformshippingItem.getFnsku().trim()
          )
          ? null
          : String.valueOf(platformshippingItem.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        platformshippingItem.getBinid(),
        Integer.parseInt(
          String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
            ? "0"
            : String.valueOf(platformshippingItem.getShipmentsnum())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        platformshippingItem.getBinid(),
        Integer.parseInt(
          String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
            ? "0"
            : String.valueOf(platformshippingItem.getShipmentsnum())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(platformshippingItem.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 锁库存_即时
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存_即时操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void locksInventory(Long id) throws Exception {
    PlatformshippingVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLocksInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    Platformshipping updateStatusEntity = new Platformshipping();
    updateStatusEntity.setId(id);
    updateStatusEntity.setShippingstatus("0");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存_即时 的参数
   */
  protected InventoryExchangeFormVo prepareLocksInventory(
    PlatformshippingVo vo
  ) throws Exception {
    if (!"0".equals(vo.getShippingstatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(PlatformshippingVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getShipmentCode());
    formVo.setDocumentType("平台仓发货");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getDeliverywarehouse());
    if (ObjectUtils.isEmpty(vo.getDeliverywarehouse())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getDeliverywarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (PlatformshippingItemItemVo platformshippingItem : vo.getItems()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(platformshippingItem.getProductName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String.valueOf(platformshippingItem.getShipmentsnum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(platformshippingItem.getShipmentsnum())
      );
      exchangeItem.setShopId(
        String
            .valueOf(platformshippingItem.getShippingwarehousestore())
            .equals("null")
          ? null
          : String.valueOf(platformshippingItem.getShippingwarehousestore())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            platformshippingItem.getFnsku() == null
              ? null
              : platformshippingItem.getFnsku().trim()
          )
          ? null
          : String.valueOf(platformshippingItem.getFnsku().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(platformshippingItem.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Override
  public void cancelOrder(Long id) throws Exception {
    if (platformshippingCancelOrderAction == null) {
      throw new Exception("此操作当前不可用");
    }
    platformshippingCancelOrderAction.run(id);
  }

  /**
   * 释放库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了释放库存操作"
  )
  @Override
  public void releaseInventory(List<Long> ids) throws Exception {
    if (platformshippingReleaseInventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    platformshippingReleaseInventoryAction.run(ids);
  }

  /**
   * 发货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了发货操作"
  )
  @Override
  public void sendoutgoods(List<Long> ids) throws Exception {
    if (platformshippingSendoutgoodsAction == null) {
      throw new Exception("此操作当前不可用");
    }
    platformshippingSendoutgoodsAction.run(ids);
  }

  /**
   * 分配库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了分配库存操作"
  )
  @Override
  public void allocateInventory(List<Long> ids) throws Exception {
    if (platformshippingAllocateInventoryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    platformshippingAllocateInventoryAction.run(ids);
  }

  /**
   * 批量完成拣货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量完成拣货操作"
  )
  @Override
  public void batchcompletionpicking(List<Long> ids) throws Exception {
    if (platformshippingBatchcompletionpickingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    platformshippingBatchcompletionpickingAction.run(ids);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    PlatformshippingSearchParamPo search = new PlatformshippingSearchParamPo();
    return MapUtil
      .builder()
      .put("AllData", this.baseMapper.allDataCount(search))
      .put(
        "WaitingDistribution",
        this.baseMapper.waitingDistributionCount(search)
      )
      .put("TobeShipped", this.baseMapper.tobeShippedCount(search))
      .put("Shipped", this.baseMapper.shippedCount(search))
      .put("Cancellation", this.baseMapper.cancellationCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<PlatformshippingItemVo> allData(
    PlatformshippingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allData(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<PlatformshippingItemVo> allDataPage(
    PlatformshippingSearchParamPo search
  ) {
    Page<PlatformshippingItemVo> allDataPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allDataPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allDataPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allDataPage =
      this.baseMapper.allDataPage(
          search.toPage(this.baseMapper.allDataCount(search)),
          search
        );
    List<Long> recordIds = allDataPage
      .getRecords()
      .stream()
      .map(PlatformshippingItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allDataPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allDataPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allDataPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allDataPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 平台仓发货单分页查询结果
   */
  @Override
  public Page<?> allDataPageWithChildSearch(
    PlatformshippingSearchParamPo search
  ) {
    return appendWithChild(allDataPage(search), search.toChildSort("items"));
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allDataLastUpdateTime(PlatformshippingSearchParamPo search) {
    return this.baseMapper.allDataLastUpdateTime(search);
  }

  /**
   * 待配货
   */
  @Override
  public List<PlatformshippingItemVo> waitingDistribution(
    PlatformshippingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitingDistribution(search);
  }

  /**
   * 待配货分页
   */
  @Override
  public Page<PlatformshippingItemVo> waitingDistributionPage(
    PlatformshippingSearchParamPo search
  ) {
    Page<PlatformshippingItemVo> waitingDistributionPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitingDistributionPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitingDistributionPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitingDistributionPage =
      this.baseMapper.waitingDistributionPage(
          search.toPage(this.baseMapper.waitingDistributionCount(search)),
          search
        );
    List<Long> recordIds = waitingDistributionPage
      .getRecords()
      .stream()
      .map(PlatformshippingItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitingDistributionPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitingDistributionPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitingDistributionPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitingDistributionPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 平台仓发货单分页查询结果
   */
  @Override
  public Page<?> waitingDistributionPageWithChildSearch(
    PlatformshippingSearchParamPo search
  ) {
    return appendWithChild(
      waitingDistributionPage(search),
      search.toChildSort("items")
    );
  }

  /**
   * 查询待配货最后更新时间
   * @param search 查询条件
   * @return 待配货最后更新时间
   */
  @Override
  public Date waitingDistributionLastUpdateTime(
    PlatformshippingSearchParamPo search
  ) {
    return this.baseMapper.waitingDistributionLastUpdateTime(search);
  }

  /**
   * 待发货
   */
  @Override
  public List<PlatformshippingItemVo> tobeShipped(
    PlatformshippingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.tobeShipped(search);
  }

  /**
   * 待发货分页
   */
  @Override
  public Page<PlatformshippingItemVo> tobeShippedPage(
    PlatformshippingSearchParamPo search
  ) {
    Page<PlatformshippingItemVo> tobeShippedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return tobeShippedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return tobeShippedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    tobeShippedPage =
      this.baseMapper.tobeShippedPage(
          search.toPage(this.baseMapper.tobeShippedCount(search)),
          search
        );
    List<Long> recordIds = tobeShippedPage
      .getRecords()
      .stream()
      .map(PlatformshippingItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return tobeShippedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return tobeShippedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    tobeShippedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return tobeShippedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 平台仓发货单分页查询结果
   */
  @Override
  public Page<?> tobeShippedPageWithChildSearch(
    PlatformshippingSearchParamPo search
  ) {
    return appendWithChild(
      tobeShippedPage(search),
      search.toChildSort("items")
    );
  }

  /**
   * 查询待发货最后更新时间
   * @param search 查询条件
   * @return 待发货最后更新时间
   */
  @Override
  public Date tobeShippedLastUpdateTime(PlatformshippingSearchParamPo search) {
    return this.baseMapper.tobeShippedLastUpdateTime(search);
  }

  /**
   * 已发货
   */
  @Override
  public List<PlatformshippingItemVo> shipped(
    PlatformshippingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.shipped(search);
  }

  /**
   * 已发货分页
   */
  @Override
  public Page<PlatformshippingItemVo> shippedPage(
    PlatformshippingSearchParamPo search
  ) {
    Page<PlatformshippingItemVo> shippedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return shippedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return shippedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    shippedPage =
      this.baseMapper.shippedPage(
          search.toPage(this.baseMapper.shippedCount(search)),
          search
        );
    List<Long> recordIds = shippedPage
      .getRecords()
      .stream()
      .map(PlatformshippingItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return shippedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return shippedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    shippedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return shippedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 平台仓发货单分页查询结果
   */
  @Override
  public Page<?> shippedPageWithChildSearch(
    PlatformshippingSearchParamPo search
  ) {
    return appendWithChild(shippedPage(search), search.toChildSort("items"));
  }

  /**
   * 查询已发货最后更新时间
   * @param search 查询条件
   * @return 已发货最后更新时间
   */
  @Override
  public Date shippedLastUpdateTime(PlatformshippingSearchParamPo search) {
    return this.baseMapper.shippedLastUpdateTime(search);
  }

  /**
   * 已作废
   */
  @Override
  public List<PlatformshippingItemVo> cancellation(
    PlatformshippingSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.cancellation(search);
  }

  /**
   * 已作废分页
   */
  @Override
  public Page<PlatformshippingItemVo> cancellationPage(
    PlatformshippingSearchParamPo search
  ) {
    Page<PlatformshippingItemVo> cancellationPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return cancellationPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return cancellationPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    cancellationPage =
      this.baseMapper.cancellationPage(
          search.toPage(this.baseMapper.cancellationCount(search)),
          search
        );
    List<Long> recordIds = cancellationPage
      .getRecords()
      .stream()
      .map(PlatformshippingItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return cancellationPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return cancellationPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    cancellationPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return cancellationPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 平台仓发货单分页查询结果
   */
  @Override
  public Page<?> cancellationPageWithChildSearch(
    PlatformshippingSearchParamPo search
  ) {
    return appendWithChild(
      cancellationPage(search),
      search.toChildSort("items")
    );
  }

  /**
   * 查询已作废最后更新时间
   * @param search 查询条件
   * @return 已作废最后更新时间
   */
  @Override
  public Date cancellationLastUpdateTime(PlatformshippingSearchParamPo search) {
    return this.baseMapper.cancellationLastUpdateTime(search);
  }
}
